package com.ytjj.qmyx.supplychain.common.utils;

import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;

/**
 * LINK平台工具类
 */
@Slf4j
public class LINKUtil {
    public static void main(String[] args) {
        System.out.println(doSign("hello1234", "utf-8", "key123"));
    }

    /**
     * MD5签名
     * @param content 请求参数
     * @param charset 字符集 支持utf-8和gbk
     * @param keys    签名密钥
     * @return
     */
    public static String doSign(String content, String charset, String keys) {
        String sign = "";
        content = content + keys;
        try {

            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(content.getBytes(charset));
            sign = new String(Base64.encodeBase64(md.digest()), charset);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return sign;
    }

    /**
     * 报文加密
     * @param encryKey  加密key
     * @param charSet   字符集
     * @param content   加密明文
     * @return
     */
    public static String encrypt(String encryKey, String charSet, String content) {
        if (StringUtils.isBlank(encryKey)) {
            throw new ApiException("[sec.encryption] is null");
        }
        // 加密
        try {
            byte[] key = Base64.decodeBase64(encryKey.getBytes(charSet));
            // content Base64解码
            byte[] inputData = content.getBytes(charSet);
            byte[] outputData = AESCoder.encrypt(inputData, key);
            content = new String(Base64.encodeBase64(outputData), charSet);
        } catch (Exception e) {
            log.error("异常", e);
        }
        return content;
    }

    /**
     * 解密
     * @param content           解密密文
     * @param requestCharSet    字符集
     * @param encryKey          加密key
     * @return
     */
    public static  String decrypt(String content, String requestCharSet,
                                  String encryKey) {
        if (StringUtils.isNotBlank(encryKey)) {
            // 解密
            try {
                byte[] key = Base64.decodeBase64(encryKey
                        .getBytes(requestCharSet));
                // content Base64解码
                byte[] contentBytes = Base64.decodeBase64(content
                        .getBytes(requestCharSet));
                byte[] outputData = AESCoder.decrypt(contentBytes, key);
                content = new String(outputData, requestCharSet);
            } catch (Exception e) {
                log.error("异常", e);
            }
        }
        return content;
    }
}
